import axios from "axios";
import router from "@/router";
import qs from "qs";
import merge from "lodash/merge";
import { clearLoginInfo } from "@/utils";

import { message as Message } from './resetMessage';
const http = axios.create({
  timeout: 1000 * 120,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
});

/**
 * 请求拦截
 */
http.interceptors.request.use(
  config => {
    // config.headers["token"] = Vue.cookie.get("token"); // 请求头带上token
    // 建议替换为其他方式获取 token，例如从 localStorage 或 sessionStorage 获取
    config.headers["Authorization"] = localStorage.getItem("token");
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


/**
 * 响应拦截
 */
http.interceptors.response.use(
  response => {
    if(response.data.code=='500')
    {
      Message({
        message: response.data.msg,
        type: 'error',
        dangerouslyUseHTMLString: true,
      });
      // return
    }
    return response;
  },

  error => {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
        /*  Message({              <!--TAPD:ID1005041-->
            message: error.response.data.msg,
            type: 'error',
          });*/
          clearLoginInfo();
          router.push({ name: "login" });
          break;
      }
    }else{
      return Promise.reject(error);
    }
  }
);

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = actionName => {
  if (actionName.startsWith("/sys/") || actionName.startsWith("/syssetup/")) {
    actionName = "/erp-system" + actionName;
  } else if (!actionName.startsWith("/erp-system")) {
    actionName = "/erp-web" + actionName;
  }
   console.log(import.meta.env.VITE_APP_BASE_URL  + actionName);
   
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return  import.meta.env.VITE_APP_BASE_URL  + actionName
    
};

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    t: new Date().getTime()
  };
  return openDefultParams ? merge(defaults, params) : params;
};

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, openDefultdata = true, contentType = "json") => {
  console.log(444444);
  
  var defaults = {
    t: new Date().getTime()
  };
  data = openDefultdata ? merge(defaults, data) : data;

  // 对每个属性值进行去空格处理
  for (let key in data) {
    if (typeof data[key] === 'string') {
      data[key] = data[key].trim();
    } else if (Array.isArray(data[key])) {
      // 如果是数组，则遍历数组进行去空格处理
      data[key] = data[key].map(item => {
        if (typeof item === 'string') {
          return item.trim();
        }
        return item;
      });
    }
  }

  return contentType === "json" ? JSON.stringify(data) : qs.stringify(data);
};

export default http;
